<template>
  <div class="menu">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button @click="$router.push({ name: 'menu-create' })">添加菜单</el-button>
      </div>
      <el-table :data="menus" style="width: 100%;">
        <el-table-column prop="date" label="编号" type="index" width="180"> </el-table-column>
        <el-table-column prop="name" label="菜单名称" width="180"> </el-table-column>
        <el-table-column prop="level" label="菜单级数" width="180"> </el-table-column>
        <el-table-column prop="icon" label="前端图标"> </el-table-column>
        <el-table-column prop="orderNum" label="排序"> </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import { getAllMenus, deleteMenu } from '/@/services/menu'
import router from '/@/router/Index'
import { ElMessage, ElMessageBox } from 'element-plus'

export default defineComponent({
  name: 'MenuIndex',
  setup() {
    const menus = ref([])
    const loadAllMenus = ref(async () => {
      const { data } = await getAllMenus()
      if (data.code === '000000') {
        menus.value = data.data
      }
    })
    const handleEdit = ref((item: any) => {
      // console.log('handleEdit', item)
      router.push({
        name: 'menu-edit',
        params: {
          id: item.id
        }
      })
    })
    const handleDelete = ref((item: any) => {
      ElMessageBox.confirm('确认删除吗?', '删除提示', {})
        .then(async () => {
          // 确认
          // 请求删除操作
          const { data } = await deleteMenu(item.id)
          if (data.code === '000000') {
            ElMessage.success('删除成功')
            loadAllMenus.value() // 更新数据
          }
        })
        .catch(() => {
          // 取消
          ElMessage.info('已取消删除')
        })
    })
    return {
      menus,
      loadAllMenus,
      handleEdit,
      handleDelete
    }
  },
  created() {
    this.loadAllMenus()
  }
})
</script>

<style lang="scss" scoped></style>
